﻿using Dapper;
using Infrastructure.DataBaseConnect;
using Infrastructure.IRepository.Sys;
using Model;
using Model.BusinessModel;
using Model.BusinessModel.OutPut;
using Model.BusinessModel.OutPut.sys;
using Model.DomainModel.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Repository.Sys
{
    /// <summary>
    /// 用户服务仓储接口实现
    /// </summary>
    public class SysUserRepository : Repository<SysUser>, ISysUserRepository
    {

        /// <summary>
        /// 根据条件获取用户
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <param name="departmentId">部门key</param>
        /// <returns></returns>
        public List<SysUserOutPut> GetUser(string corporationKey, string? departmentId)
        {
            StringBuilder sql = new(@" select su.*,sc.CorporationName,sd.DepartmentName from Sys_User as su
                                      inner join Sys_Corporation as sc on su.CorporationKey = sc.CorporationKey
                                      inner join Sys_Department as sd on su.DepartmentId = sd.Id ");
            var qp = new QueryParameter();
            if (!string.IsNullOrWhiteSpace(corporationKey) && Const.XC_CorporationKey != corporationKey)
            {
                qp.listWhere.Append(" and su.CorporationKey = @CorporationKey ");
                qp.dynamicParameter.Add("@CorporationKey", corporationKey);
            }
            if (!string.IsNullOrWhiteSpace(departmentId))
            {
                qp.listWhere.Append(" and su.DepartmentId = @DepartmentId ");
                qp.dynamicParameter.Add("@DepartmentId", departmentId);
            }
            if (!string.IsNullOrEmpty(qp.listWhere.ToString()))
            {
                sql.Append(" WHERE 1=1 " + qp.listWhere.ToString());
            }
            sql.Append(" order by su.CreateTime desc");
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.Query<SysUserOutPut>(sql.ToString(), qp.dynamicParameter).ToList();
        }

        /// <summary>
        /// 根据用户名称和密码获取用户信息
        /// </summary>
        /// <param name="userName">用户名称</param>
        /// <param name="password">用户密码</param>
        /// <param name="corporationKey">公司编码</param>
        /// <returns></returns>
        public SysUser? GetUserMsg(string userName, string password, string corporationKey)
        {
            string sql = " select * from Sys_User where UserName =@UserName and Password=@Password and CorporationKey=@CorporationKey";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.QueryFirstOrDefault<SysUser>(sql, new { UserName = userName, Password = password, CorporationKey = corporationKey });
        }

        /// <summary>
        /// 根据用户名称获取数据
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <param name="userName">用户名称</param>
        /// <returns></returns>
        public SysUser? GetUserByName(string corporationKey, string userName)
        {
            string sql = " select * from Sys_User where UserName =@UserName and CorporationKey=@CorporationKey";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.QueryFirstOrDefault<SysUser>(sql, new { UserName = userName, CorporationKey = corporationKey });
        }

        /// <summary>
        /// 根据部门id集合获取人员
        /// </summary>
        /// <param name="ids">部门id集合</param>
        /// <returns></returns>
        public List<SysUser> GetUserByDepId(List<string> ids)
        {
            string sql = "   select * from  Sys_User  where DepartmentId in @Key ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.Query<SysUser>(sql, new { Key = ids }).ToList();
        }

        /// <summary>
        /// 设置用户的部门
        /// </summary>
        /// <param name="userIds">用户集合</param>
        /// <param name="depId">部门ID</param>
        public void SetUserDep(List<string> userIds, string depId)
        {
            string sql = " update Sys_User set DepartmentId = @DepartmentId where UserId in @Key ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            connection.Execute(sql, new { Key = userIds, DepartmentId = depId });
        }

        /// <summary>
        /// 设置用户是否启用
        /// </summary>
        /// <param name="keys">key集合</param>
        /// <param name="isOpen">是否启用</param>
        public void SetUserIsOpen(List<string> keys, bool isOpen)
        {
            string sql = "   update Sys_User set IsOpen=@IsOpen where UserId in @UserId  ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            connection.Query(sql, new { UserId = keys, IsOpen = isOpen });
        }

        /// <summary>
        /// 获取公司人员
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public List<TreeOutPut> GetCorporationUser(string corporationKey)
        {
            StringBuilder sql = new(@" select * from (
                                select UserId as [Key],DepartmentId AS [PKey]  , UserName as  label,CorporationKey,'User' icon,6 as nodeType
                                from  Sys_User 
                                UNION 
                                SELECT Id  as [Key], CorporationKey as  [PKey] , DepartmentName as  [Value],CorporationKey,'Memo' icon,3 as nodeType
                                 from Sys_Department
								  UNION 
                                SELECT CorporationKey  as [Key], '' as  [PKey] , CorporationName as  [Value],CorporationKey,'OfficeBuilding' icon,1 as nodeType
                                 from Sys_Corporation) as t");

            var qp = new QueryParameter();
            if (!string.IsNullOrWhiteSpace(corporationKey))
            {
                qp.listWhere.Append(" and t.CorporationKey = @CorporationKey ");
                qp.dynamicParameter.Add("@CorporationKey", corporationKey);
            }

            if (!string.IsNullOrEmpty(qp.listWhere.ToString()))
            {
                sql.Append(" WHERE 1=1 " + qp.listWhere.ToString());
            }
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.Query<TreeOutPut>(sql.ToString(), qp.dynamicParameter).ToList();
        }

        /// <summary>
        /// 根据公司key,获取用户
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public List<SysUser> GetUserByCorporationKey(string corporationKey)
        {
            string sql = "   select * from  Sys_User where CorporationKey = @CorporationKey ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.Query<SysUser>(sql, new { CorporationKey = corporationKey }).ToList();
        }
    }
}
